package com.brotherly.mpgp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.brotherly.framework.BaseActivity;
import com.brotherly.framework.app.BaseApplication;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.mpgp.remoteinterface.RemoteServerService;
import com.brotherly.mpgp.remoteinterface.RemoteServerWatcher;
import com.brotherly.mpgp.view.DownLoadButton;
import com.brotherly.mpgp.view.FlipImageView;
import com.brotherly.mpgp.view.UpdateFreshListView;
import com.brotherly.mpgp.view.UpdateFreshListView.OnRefreshListener;
import com.brotherly.util.BitmapUtil;
import com.brotherly.util.downloader.DownLoaderUtil;

public class GameDetailActivity extends BaseActivity {

    private boolean isCreate = true;

    private JSONObject mGameData = null;

    private View mGameBrief = null;
    private View mGameStrategy = null;

    private ViewGroup mViewsContainer = null;

    private View mGameBriefMain = null;
    private View mGameStrategyMain = null;

    private LayoutInflater mInflater = null;

    private UpdateFreshListView mStrategyContents = null;
    private CheatsListAdapter mStartegyAdapter = null;
    private ArrayList<JSONObject> mCheats = new ArrayList<JSONObject>();
    private int mStrategyTotalCount = 0;
    private int mNextIndex = 0;

    private int mGameRef = -1;
    private String mGameIdentifier = "";

    private long mGameSize = 0;
    private String mGameName = "";
    private int mGameId = 0;
    private ArrayList<String> mGameTags = new ArrayList<String>();

    private View mGameBriefContainer = null;
    private TextView mTitleView = null;
    private LinearLayout mTagsContainer = null;
    private TextView mGameSizeView = null;
    private LinearLayout mIndicator = null;
    private ImageView mGameImage = null;
    private LinearLayout mContentContainer = null;
    private View mFlipImagesContainer = null;
    private View mPartLiner = null;
    private DownLoadButton mDownLoadButton = null;
    private FlipImageView mBriefImageFlip = null;
    private View mNextImage = null;
    private View mPreImage = null;
    private View mFavorateGameBtn = null;
    private View mBriefProg = null;
    private View mGameShare = null;
    private HashMap<String, Bitmap> mBriefImage = new HashMap<String, Bitmap>();

    private TextView mTabBrief = null;
    private TextView mTabStrategy = null;

    public static final int COUNT_PER_AGE = 10;

    private boolean mIsCleanStrategy = true;

    private OnRefreshListener refreshListener = new OnRefreshListener()
    {
        @Override
        public void onRefresh(UpdateFreshListView listview)
        {
            mIsCleanStrategy = true;
            gameCourse(0, COUNT_PER_AGE);
        }

        @Override
        public void onLoadMore(UpdateFreshListView listview)
        {
            mIsCleanStrategy = false;
            gameCourse(mNextIndex, COUNT_PER_AGE);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_detail);

        isCreate = true;

        mTabBrief = (TextView) findViewById(R.id.game_detail_brief_tab);
        mTabStrategy = (TextView) findViewById(R.id.game_detail_strategy_tab);

        mGameRef = getIntent().getIntExtra("gameref", -1);
        mGameIdentifier = getIntent().getStringExtra("packageName");

        mInflater = LayoutInflater.from(this);

        mGameBrief = findViewById(R.id.game_brief);
        mGameStrategy = findViewById(R.id.game_strategy);

        mGameBrief.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                towardToBrief();
            }
        });

        mGameStrategy.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                towardToStrategy();
            }
        });

        mViewsContainer = (ViewGroup) findViewById(R.id.content_container);

        mGameBriefMain = mInflater.inflate(R.layout.game_detail_brief_main, null);
        mBriefImageFlip = (FlipImageView) mGameBriefMain.findViewById(R.id.game_detail_brief_flipImage);
        mIndicator = (LinearLayout) mGameBriefMain.findViewById(R.id.game_detail_brief_images_indicator);
        mBriefImageFlip.setIndicatorContainer(mIndicator);
        mFlipImagesContainer = mGameBriefMain.findViewById(R.id.game_detail_brief_flipimagecontainer);
        mGameSizeView = (TextView) mGameBriefMain.findViewById(R.id.game_detail_gamesize);
        mTagsContainer = (LinearLayout) mGameBriefMain.findViewById(R.id.game_detail_brief_tags_container);
        mTitleView = (TextView) mGameBriefMain.findViewById(R.id.game_detail_brief_game_title);
        mGameImage = (ImageView) mGameBriefMain.findViewById(R.id.game_detail_icon);
        mContentContainer = (LinearLayout) mGameBriefMain.findViewById(R.id.game_detail_brief_contentcontainer);
        mDownLoadButton = (DownLoadButton) mGameBriefMain.findViewById(R.id.downloadbtn);
        mDownLoadButton.setStyle(DownLoadButton.STYLE_GAME_DETAIL_DOWNLOAD_BTN);
        mPartLiner = mGameBriefMain.findViewById(R.id.part_line);
        mNextImage = mGameBriefMain.findViewById(R.id.btn_right_arrow);
        mNextImage.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                mBriefImageFlip.showNext();
            }
        });
        mPreImage = mGameBriefMain.findViewById(R.id.btn_left_arrow);
        mPreImage.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                mBriefImageFlip.showPre();
            }
        });
        mFavorateGameBtn = mGameBriefMain.findViewById(R.id.btn_add_favorite);
        mFavorateGameBtn.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String msg = "";
                try
                {
                    boolean hasFavorite = isFavoriteGame(mGameId);
                    if (hasFavorite)
                    {
                        delFavoriteGame(mGameData.getInt("id"));
                        msg = "取消收藏成功！";
                    } else
                    {
                        favoriteGame(mGameData.getInt("id"), mGameData);
                        msg = "收藏成功！";
                    }
                    updateFavorateBtn();
                }
                catch (Exception e)
                {
                    Toast.makeText(GameDetailActivity.this, "操作失败！", Toast.LENGTH_SHORT).show();
                }
                Toast.makeText(GameDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
        mBriefProg = mGameBriefMain.findViewById(R.id.brief_main_prog);
        mGameShare = mGameBriefMain.findViewById(R.id.btn_share);
        mGameShare.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                shareGame(mGameName, mGameRef);
            }
        });
        mGameBriefContainer = mGameBriefMain.findViewById(R.id.game_brief_container);

        mGameStrategyMain = mInflater.inflate(R.layout.main_cheats_list_viewpager_item, null);
        mStrategyContents = (UpdateFreshListView) mGameStrategyMain.findViewById(R.id.lv_cheats);
        mGameStrategyMain.findViewById(R.id.ll_main_top).setVisibility(View.GONE);
        mStartegyAdapter = new CheatsListAdapter(this);
        mStrategyContents.setAdapter(mStartegyAdapter);
        mStrategyContents.setIsShowLoadMoreFooter(false);
        mStrategyContents.setOnRefreshListener(refreshListener);
        mStrategyContents.setOnItemClickListener(mStartegyAdapter);
        mStartegyAdapter.notifyDataSetChanged();
    }

    private void downLoadGameInfo()
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        rss.gameDetail(mGameRef);
        mBriefProg.setVisibility(View.VISIBLE);
        mGameBriefContainer.setVisibility(View.GONE);
    }

    private void updateBriefImages(String url)
    {
        if (mBriefImage.containsKey(url))
            return;
        Bitmap b = loadImageFromLocal(url);
        if (b != null)
        {
            mBriefImage.put(url, b);
        }

        ArrayList<Bitmap> bs = new ArrayList<Bitmap>();
        for (String key : mBriefImage.keySet())
        {
            Bitmap bb = mBriefImage.get(key);
            bs.add(bb);
        }

        // bs.add(BitmapFactory.decodeResource(getResources(),
        // R.drawable.btn_back_normal));
        // bs.add(BitmapFactory.decodeResource(getResources(),
        // R.drawable.article_promotion));

        mBriefImageFlip.setShowImages(bs);
        mFlipImagesContainer.setVisibility(View.VISIBLE);
        updatePartLineShow();
    }

    private Bitmap loadImageFromLocal(String url)
    {
        String cachePath = internetResourceDownload(url);
        if (cachePath != null)
        {
            Bitmap bitmap = BitmapUtil.loadBitmap(cachePath);
            if (bitmap == null)
            {
                // removeCachedData(url);
                // internetResourceDownload(url);
            } else
            {
                return bitmap;
            }
        }
        return null;
    }

    private void towardToBrief()
    {
        mViewsContainer.removeAllViews();
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mViewsContainer.addView(mGameBriefMain, lp);
        mGameBrief.setBackgroundResource(R.drawable.game_detail_selected_tab_bg);
        mTabBrief.setTextColor(getResources().getColor(R.color.game_detial_tab_text_color));
        mGameStrategy.setBackgroundColor(0xff000000);
        mTabStrategy.setTextColor(0xFFFFFFFF);
        if (mGameData == null)
        {
            downLoadGameInfo();
        }
    }

    private void towardToStrategy()
    {
        mViewsContainer.removeAllViews();
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mViewsContainer.addView(mGameStrategyMain, lp);
        mGameStrategy.setBackgroundResource(R.drawable.game_detail_selected_tab_bg);
        mTabStrategy.setTextColor(getResources().getColor(R.color.game_detial_tab_text_color));
        mGameBrief.setBackgroundColor(0xff000000);
        mTabBrief.setTextColor(0xFFFFFFFF);
        if (mCheats == null || mCheats.isEmpty())
        {
            mStrategyContents.requestFresh();
            mStrategyContents.setIsShowLoadMoreFooter(false);
        }
    }

    @Override
    protected void onServiceEvent(String id, Object param1, Object param2)
    {
        if (RemoteServerService.RemoteServer_Event_RemoteServer_Success.equals(id))
        {
            if (RemoteServerService.ACTION_GAME_DETAIL.equals(param1))
            {
                isCreate = false;
                final JSONObject data = (JSONObject) param2;
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        mGameData = data;
                        mBriefProg.setVisibility(View.GONE);
                        mGameBriefContainer.setVisibility(View.VISIBLE);
                        updateBriefViewShow();
                    }
                });
            } else if (RemoteServerService.ACTION_GAME_ARTICLES.equals(param1))
            {
                final JSONObject data = (JSONObject) param2;
                updateStrategyViewShow(data);
            }
        } else if (RemoteServerService.RemoteServer_Event_RemoteServer_Error.equals(id))
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    Toast.makeText(GameDetailActivity.this, "您的网络不给力，请重试一下。", Toast.LENGTH_SHORT).show();
                    mBriefProg.setVisibility(View.GONE);
                }
            });
        }
        else if (Activity_Event_Internet_Resource_Download_Success.equals(id))
        {
            // final String url = (String) param1;
            runOnUiThread(new Runnable()
            {

                @Override
                public void run()
                {
                    updateBriefViewShow();
                    mStartegyAdapter.notifyDataSetChanged();
                }
            });
        } else if (DownLoaderUtil.Activity_Event_FileDownload_Info.equals(id))
        {
            if (1 == (Integer) param1)
            {
                JSONObject json = (JSONObject) param2;
                String url = null;
                try
                {
                    url = json.getString("url");
                    if (null != url)
                    {
                        final DownLoadButton dlBut = mDownLoadButton;
                        if (url.equals(dlBut.getUrl()))
                        {
                            dlBut.setDownLoading();
                        } else
                        {
                            return;
                        }

                        if (dlBut != null)
                        {
                            dlBut.setFileSize(json.getInt("fileSize"));
                            dlBut.setComplete(json.getInt("compelete"));
                            runOnUiThread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    dlBut.showProgress();
                                }
                            });

                            Log.d(url, "Param = 1 FileSize : " + dlBut.getFileSize()
                                    + "    Complete:" + dlBut.getComplete());
                            if (dlBut.getFileSize() <= dlBut.getComplete())
                            {
                                Log.i("TAG", "下载完成");
                                dlBut.stopDownload();
                                final DownLoadButton dlBut2 = dlBut;
                                runOnUiThread(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        dlBut2.setStatusText();
                                    }
                                });
                                // checkInstallApk(json);
                            }
                        }

                    }

                }
                catch (JSONException e)
                {
                    Log.e("TAG", "onServiceEvent donwload not url");
                }
            }
            else if (-1 == (Integer) param1)
            {
                showSDCardError();
            }
            else if (-2 == (Integer) param1)
            {
                showDownloadLongClick(param2);
            }
            else if (0 == (Integer) param1)
            {
                final DownLoadButton dlBut = mDownLoadButton;
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        dlBut.setPause();
                        dlBut.invalidate();
                        Toast.makeText(GameDetailActivity.this, "您的网络不给力啊，无法继续下载请调整好了在点我。", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    private void updateStrategyViewShow(JSONObject data)
    {
        try
        {
            if (mIsCleanStrategy)
            {
                mCheats.clear();
            }

            mStrategyTotalCount = data.getInt("count");
            JSONArray contents = data.getJSONArray("body");
            for (int i = 0; i < contents.length(); i++)
            {
                JSONObject content = contents.getJSONObject(i);
                mCheats.add(content);
            }
            mNextIndex = mCheats.size() / COUNT_PER_AGE;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        runOnUiThread(new Runnable()
        {

            @Override
            public void run()
            {
                mGameStrategyMain.setVisibility(View.VISIBLE);
                boolean hasMore = mStrategyTotalCount > mCheats.size();
                mStrategyContents.setIsShowLoadMoreFooter(hasMore);
                mStrategyContents.onRefreshComplete();
                mStrategyContents.notifyLoadMoreComplet();
                mStartegyAdapter.notifyDataSetChanged();
            }
        });
    }

    private void updateGameIcon()
    {
        try
        {
            mGameId = mGameData.getInt("id");
            String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                    .append("games/blob?key=image&gameref=")
                    .append(mGameId).toString();
            if (imageurl == null)
                return;
            mGameImage.setTag(imageurl);
            String cachePath = internetResourceDownload(imageurl);
            if (cachePath != null)
            {
                Bitmap i = BitmapUtil.loadBitmap(cachePath);
                if (i == null)
                {
                    mGameImage.setImageResource(R.drawable.grap_icon);
                } else
                {
                    mGameImage.setImageBitmap(i);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private void updatePartLineShow()
    {
        if (mContentContainer.getVisibility() == View.VISIBLE && mFlipImagesContainer.getVisibility() == View.VISIBLE)
        {
            mPartLiner.setVisibility(View.VISIBLE);
        } else
        {
            mPartLiner.setVisibility(View.GONE);
        }
    }

    private void updateContent()
    {
        mContentContainer.setVisibility(View.VISIBLE);
        LinearLayout container = (LinearLayout) mGameBriefMain.findViewById(R.id.game_detail_brief_content);
        updatePartLineShow();
        int padding = converToPx(10);
        container.removeAllViews();
        try
        {
            JSONArray contents = new JSONArray(mGameData.getString("content"));
            for (int i = 0; i < contents.length(); i++)
            {
                JSONObject content = contents.getJSONObject(i);
                String type = content.getString("type");
                if ("title".equals(type))
                {
                    TextView title = new TextView(this);
                    title.setPadding(0, padding, 0, padding);
                    title.setText(content.getString("content"));
                    title.setTextColor(0xFF000000);
                    title.setTextSize(20);
                    container.addView(title);
                    continue;
                }
                if ("tip".equals(type))
                {
                    TextView tip = new TextView(this);
                    tip.setPadding(0, padding, 0, padding);
                    tip.setText(content.getString("content"));
                    tip.setTextColor(0xFF000000);
                    tip.setTextSize(18);
                    container.addView(tip);
                    continue;
                }
                if ("para".equals(type))
                {
                    TextView para = new TextView(this);
                    para.setPadding(0, padding, 0, padding);
                    para.setText(content.getString("content"));
                    para.setTextColor(0xFF000000);
                    para.setTextSize(15);
                    container.addView(para);
                    continue;
                }
                if ("image".equals(type))
                {
                    String key = content.getString("content");
                    String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("games/blob?gameref=")
                            .append(mGameRef).append("&key=").append(key).toString();
                    String cachePath = internetResourceDownload(imageurl);
                    if (cachePath != null)
                    {
                        Bitmap bitmap = BitmapUtil.loadBitmap(cachePath);
                        if (bitmap == null)
                        {} else
                        {
                            updateBriefImages(imageurl);
                        }
                    }
                    continue;
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private int converToPx(int dp)
    {
        return (int) (dp * getResources().getDisplayMetrics().density);
    }

    private void updateBriefViewShow()
    {
        try
        {
            if (mGameData.has("id"))
            {
                updateGameIcon();
            }

            if (mGameData.has("name"))
            {
                mGameName = mGameData.getString("name");
                mTitleView.setText(mGameName);
            }

            mTagsContainer.removeAllViews();
            if (mGameData.has("tags"))
            {
                JSONArray tags = mGameData.getJSONArray("tags");
                mGameTags.clear();
                for (int i = 0; i < tags.length(); i++)
                {
                    mGameTags.add(tags.getString(i));
                }
                mTagsContainer.removeAllViews();
                for (int i = 0; i < mGameTags.size() && i < 2; i++)
                {
                    String tag = mGameTags.get(i);
                    TextView t = new TextView(GameDetailActivity.this);
                    t.setText(tag);
                    int w = converToPx(48);
                    int h = converToPx(24);
                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(w,
                            h);
                    lp.rightMargin = 11;
                    t.setLayoutParams(lp);
                    if (i == 0)
                    {
                        t.setBackgroundColor(0xffe8931c);
                    } else if (i == 1)
                    {
                        t.setBackgroundColor(0xff90a748);
                    }
                    t.setTextColor(Color.WHITE);
                    t.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                    t.setGravity(Gravity.CENTER);
                    mTagsContainer.addView(t);
                }
            }

            if (mGameData.has("info"))
            {
                JSONObject info = mGameData.getJSONObject("info");
                if (info.has("size"))
                {
                    mGameSize = info.getLong("size");
                    long size = mGameSize / 1024 / 1024;

                    mGameSizeView.setText(size + " M");
                }
                if (!info.has("package"))
                {
                    mDownLoadButton.setEnabled(false);
                }
            }

            if (mGameData.has("content"))
            {
                updateContent();
            }

            if (mGameId != -1 && mGameName != null && mGameSize != -1)
            {
                mDownLoadButton.setKey(mGameId, mGameName);
                mDownLoadButton.setFileSize((int) mGameSize);
                mDownLoadButton.checkLocalFile();
            }
            updateFavorateBtn();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onAllReady()
    {
        if (BaseApplication.getInstance().isNeedReloadGameInfo())
        {
            finish();
        } else
        {
            if (isCreate)
            {
                towardToStrategy();
            }
        }
    }

    private void gameCourse(int index, int count)
    {
        RemoteServerService rss = (RemoteServerService) ServiceManager.getInstance().getService(
                ServiceManager.REMOTESEVER_SERVICE);
        // showProgressDialog("正在加载，请稍后...");
        ArrayList<String> gameids = new ArrayList<String>();
        gameids.add(mGameIdentifier);
        rss.gameArticles(gameids, index, count);
    }

    private class CheatsListAdapter extends BaseAdapter implements OnItemClickListener
    {
        private List<JSONObject> mArticles;

        private boolean mIsShowPic = true;

        private LayoutInflater mInflater;

        public CheatsListAdapter(Context context)
        {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            return mArticles == null ? 0 : mArticles.size();
        }

        @Override
        public Object getItem(int position)
        {
            return mArticles.get(position);
        }

        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = (ViewGroup) mInflater.inflate(R.layout.article_list_item, null);
            }
            if (position % 2 == 0)
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_1);
            } else
            {
                convertView.setBackgroundResource(R.drawable.list_item_background_2);
            }
            try
            {
                JSONObject item = (JSONObject) getItem(position);
                String type = item.getString("type");

                TextView title = (TextView) convertView.findViewById(R.id.tv_article_list_item_title);
                title.setText(item.getString("title"));
                View typeView = convertView.findViewById(R.id.v_type);
                Button getAccount = (Button) convertView.findViewById(R.id.btn_get_account);
                JSONObject info = null;
                JSONObject action = null;
                if (item.has("info"))
                {
                    info = item.getJSONObject("info");
                    if (info.has("action"))
                    {
                        JSONArray actions = info.getJSONArray("action");
                        if (actions.length() > 0)
                        {
                            action = actions.getJSONObject(0);
                        }
                    }
                }
                ImageView imageview = (ImageView) convertView.findViewById(R.id.iv_article_list_item_image);
                // imageview.setVisibility(View.GONE);
                if (mIsShowPic)
                {
                    imageview.setVisibility(View.VISIBLE);
                    loadArticleFirstImage(item, imageview);
                    title.setLines(2);
                } else
                {
                    imageview.setVisibility(View.GONE);
                    title.setLines(1);
                }
                if (action != null)
                {
                    getAccount.setVisibility(View.VISIBLE);
                } else
                {
                    getAccount.setVisibility(View.GONE);
                }
                if ("course".equals(type))
                {
                    typeView.setBackgroundColor(0xff7ac3c9);
                } else
                {
                    typeView.setBackgroundColor(0xfffc7a7e);
                }

                TextView content = (TextView) convertView.findViewById(R.id.tv_article_content);
                if (mIsShowPic)
                {
                    content.setVisibility(View.GONE);
                } else
                {
                    content.setVisibility(View.VISIBLE);
                    String contentStr = item.getString("content");
                    JSONArray contents = new JSONArray(contentStr);
                    for (int i = 0; i < contents.length(); i++)
                    {
                        if ("para".equals(contents.getJSONObject(i).getString("type")))
                        {
                            content.setText(contents.getJSONObject(i).getString("content"));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return convertView;
        }

        @Override
        public void notifyDataSetChanged()
        {
            mArticles = new ArrayList<JSONObject>(mCheats);
            SharedPreferences sp = getSharedPreferences("Setting", MODE_PRIVATE);
            mIsShowPic = sp.getBoolean("isShowPic", false);
            super.notifyDataSetChanged();
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            Intent intent = new Intent(GameDetailActivity.this, ArticleActivity.class);
            intent.putExtra("Articles", mArticles.toString());
            intent.putExtra("Index", position - 1);
            startActivity(intent);
        }
    }

    public void loadArticleFirstImage(JSONObject article, ImageView imageview)
    {
        try
        {
            JSONArray contents = new JSONArray(article.getString("content"));
            boolean isHaveImage = false;
            for (int i = 0; i < contents.length(); i++)
            {
                JSONObject content = contents.getJSONObject(i);
                String type = content.getString("type");
                if ("image".equals(type))
                {
                    String key = content.getString("content");
                    int id = article.getJSONObject("info").getJSONArray(key).getJSONObject(0).getInt("id");
                    String imageurl = new StringBuffer(RemoteServerWatcher.RemoteServerRoot)
                            .append("articles/blob?ref=")
                            .append(id).toString();
                    // String cachePath = internetResourceDownload(imageurl);
                    // if (cachePath != null)
                    // {
                    // Bitmap bitmap = BitmapUtil.loadBitmap(cachePath);
                    // if (bitmap == null)
                    // {
                    // imageview.setImageResource(R.drawable.nopicture);
                    // // imageview.setScaleType(ScaleType.CENTER_INSIDE);
                    // } else
                    // {
                    // imageview.setImageBitmap(bitmap);
                    // // imageview.setScaleType(ScaleType.CENTER_CROP);
                    // }
                    // }
                    imageViewLoadInternetResource(imageview, imageurl, 0);

                    imageview.setTag(imageurl);
                    isHaveImage = true;
                    break;
                }
            }
            if (!isHaveImage)
            {
                imageview.setImageDrawable(new ColorDrawable(0x00000000));
                // imageview.setScaleType(ScaleType.CENTER_INSIDE);
            }
        }
        catch (Exception e)
        {}
    }

    private void updateFavorateBtn()
    {
        try
        {
            JSONObject item = mGameData;
            boolean hasFav = isFavoriteGame(item.getInt("id"));
            if (hasFav)
            {
                mFavorateGameBtn.setBackgroundResource(R.drawable.game_detail_favorite_pressed);
            } else
            {
                mFavorateGameBtn.setBackgroundResource(R.drawable.game_detail_favorite);
            }
        }
        catch (Exception e)
        {}
    }

    private void showSDCardError()
    {
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog alertDialog = new AlertDialog.Builder(GameDetailActivity.this)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener()
                        {
                            @Override
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.cancel();
                            }
                        }).setMessage("您手机未安装SD，请安装后在使用下载功能。").create();
                alertDialog.show();
            }
        });
    }

    private void showDownloadLongClick(Object param2)
    {
        final Object p2 = param2;
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(GameDetailActivity.this);
                alertDialog.setTitle("菜单");
                alertDialog.setItems
                        (
                                R.array.downloadmenu, new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which)
                                    {
                                        DownLoadButton dlBut = (DownLoadButton) p2;
                                        switch (which)
                                        {
                                            case 0:
                                            {
                                                dlBut.installAPK();
                                                break;
                                            }
                                            case 1:
                                            {
                                                dlBut.deleteDownLoadFile();
                                                break;
                                            }
                                        }
                                    }
                                }
                        );
                alertDialog.show();

            }
        });
    }

}
